/**
 * 应用配置管理
 */
export class AppConfig {
    /**
     * 获取环境变量
     * @param {string} key - 环境变量键
     * @param {any} defaultValue - 默认值
     * @returns {any} 环境变量值
     */
    static getEnv(key, defaultValue = null) {
        return import.meta.env[key] ?? defaultValue;
    }

    /**
     * 获取布尔类型环境变量
     * @param {string} key - 环境变量键
     * @param {boolean} defaultValue - 默认值
     * @returns {boolean}
     */
    static getBooleanEnv(key, defaultValue = false) {
        const value = this.getEnv(key, defaultValue.toString());
        return value === 'true' || value === true;
    }

    /**
     * 获取数字类型环境变量
     * @param {string} key - 环境变量键
     * @param {number} defaultValue - 默认值
     * @returns {number}
     */
    static getNumberEnv(key, defaultValue = 0) {
        const value = this.getEnv(key, defaultValue.toString());
        const parsed = parseInt(value, 10);
        return isNaN(parsed) ? defaultValue : parsed;
    }

    /**
     * 应用基础配置
     */
    static get app() {
        const env = this.getEnv('VITE_APP_ENV', 'development');
        return {
            title: this.getEnv('VITE_APP_TITLE', 'EduWebManager'),
            version: this.getEnv('VITE_APP_VERSION', '1.0.0'),
            env: env,
            isDev: env === 'development',
            isProd: env === 'production',
            isLocal: env === 'local',
            buildTime: this.getEnv('__BUILD_TIME__', new Date().toISOString())
        };
    }

    /**
     * API相关配置
     */
    static get api() {
        return {
            baseURL: this.getEnv('VITE_API_BASE_URL', ''),
            timeout: this.getNumberEnv('VITE_API_TIMEOUT', 10000),
            retryCount: this.getNumberEnv('VITE_API_RETRY_COUNT', 3),
            retryDelay: this.getNumberEnv('VITE_API_RETRY_DELAY', 1000),
            enableInterceptors: this.getBooleanEnv('VITE_API_ENABLE_INTERCEPTORS', true)
        };
    }

    /**
     * 上传相关配置
     */
    static get upload() {
        const maxSize = this.getNumberEnv('VITE_UPLOAD_MAX_SIZE', 10485760); // 10MB
        const allowedTypes = this.getEnv('VITE_UPLOAD_ALLOWED_TYPES', 'jpg,jpeg,png,gif,pdf,doc,docx').split(',');
        const chunkSize = this.getNumberEnv('VITE_UPLOAD_CHUNK_SIZE', 1048576); // 1MB

        return {
            maxSize,
            allowedTypes,
            chunkSize,
            enableProgress: this.getBooleanEnv('VITE_UPLOAD_ENABLE_PROGRESS', true),

            /**
             * 检查文件大小
             * @param {number} size - 文件大小(字节)
             * @returns {boolean} 是否符合限制
             */
            checkSize(size) {
                return size <= maxSize;
            },

            /**
             * 检查文件类型
             * @param {string} fileName - 文件名
             * @returns {boolean} 是否允许的类型
             */
            checkType(fileName) {
                const extension = fileName.toLowerCase().split('.').pop();
                return allowedTypes.includes(extension);
            },

            /**
             * 格式化文件大小
             * @param {number} bytes - 字节数
             * @returns {string} 格式化后的大小
             */
            formatSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
        };
    }

    /**
     * 调试相关配置
     */
    static get debug() {
        return {
            enableMock: this.getBooleanEnv('VITE_ENABLE_MOCK', false),
            enableDevtools: this.getBooleanEnv('VITE_ENABLE_DEVTOOLS', false),
            enableConsoleLog: this.getBooleanEnv('VITE_ENABLE_CONSOLE_LOG', false),
            enableErrorTracking: this.getBooleanEnv('VITE_ENABLE_ERROR_TRACKING', true),
            level: this.getEnv('VITE_DEBUG_LEVEL', 'error')
        };
    }

    /**
     * 缓存相关配置
     */
    static get cache() {
        return {
            enabled: this.getBooleanEnv('VITE_CACHE_ENABLED', true),
            ttl: this.getNumberEnv('VITE_CACHE_TTL', 300000),
            maxSize: this.getNumberEnv('VITE_CACHE_MAX_SIZE', 50),
            storageType: this.getEnv('VITE_CACHE_STORAGE_TYPE', 'sessionStorage')
        };
    }

    /**
     * JWT相关配置
     */
    static get jwt() {
        return {
            refreshThreshold: this.getNumberEnv('VITE_JWT_REFRESH_THRESHOLD', 300),
            autoRefresh: this.getBooleanEnv('VITE_JWT_AUTO_REFRESH', true),
            storageType: this.getEnv('VITE_JWT_STORAGE_TYPE', 'localStorage')
        };
    }

    /**
     * 性能相关配置
     */
    static get performance() {
        return {
            enableMonitor: this.getBooleanEnv('VITE_ENABLE_PERFORMANCE_MONITOR', false),
            enableBundleAnalyzer: this.getBooleanEnv('VITE_ENABLE_BUNDLE_ANALYZER', false),
            enableCompression: this.getBooleanEnv('VITE_ENABLE_COMPRESSION', true),
            enableTreeShaking: this.getBooleanEnv('VITE_ENABLE_TREE_SHAKING', true),
            enableHotReload: this.getBooleanEnv('VITE_ENABLE_HOT_RELOAD', true)
        };
    }

    /**
     * 安全相关配置
     */
    static get security() {
        return {
            enableCSP: this.getBooleanEnv('VITE_ENABLE_CSP', false),
            enableHTTPSOnly: this.getBooleanEnv('VITE_ENABLE_HTTPS_ONLY', false),
            enableHSTS: this.getBooleanEnv('VITE_ENABLE_HSTS', false),
            secureCookies: this.getBooleanEnv('VITE_SECURE_COOKIES', false)
        };
    }

    /**
     * CDN相关配置
     */
    static get cdn() {
        return {
            baseURL: this.getEnv('VITE_CDN_BASE_URL', ''),
            staticAssetsURL: this.getEnv('VITE_STATIC_ASSETS_CDN', ''),
            enabled: this.getBooleanEnv('VITE_ENABLE_CDN', false)
        };
    }

    /**
     * 错误处理相关配置
     */
    static get errorHandling() {
        return {
            boundaryEnabled: this.getBooleanEnv('VITE_ERROR_BOUNDARY_ENABLED', true),
            retryEnabled: this.getBooleanEnv('VITE_ERROR_RETRY_ENABLED', true)
        };
    }

    /**
     * 监控相关配置
     */
    static get monitoring() {
        return {
            enableAnalytics: this.getBooleanEnv('VITE_ENABLE_ANALYTICS', false),
            enableErrorReporting: this.getBooleanEnv('VITE_ENABLE_ERROR_REPORTING', false)
        };
    }

    /**
     * 开发服务器配置
     */
    static get devServer() {
        return {
            port: this.getNumberEnv('VITE_DEV_PORT', 3000),
            host: this.getEnv('VITE_DEV_HOST', 'localhost'),
            https: this.getBooleanEnv('VITE_DEV_HTTPS', false),
            open: this.getBooleanEnv('VITE_DEV_OPEN', true)
        };
    }

    /**
     * 存储相关配置
     */
    static get storage() {
        return {
            tokenKey: 'Authorization',
            userKey: 'userInfo',
            settingsKey: 'appSettings',

            /**
             * 获取存储项
             * @param {string} key - 存储键
             * @param {any} defaultValue - 默认值
             * @returns {any} 存储值
             */
            get(key, defaultValue = null) {
                try {
                    const value = localStorage.getItem(key);
                    return value ? JSON.parse(value) : defaultValue;
                } catch (error) {
                    console.error('Storage get error:', error);
                    return defaultValue;
                }
            },

            /**
             * 设置存储项
             * @param {string} key - 存储键
             * @param {any} value - 存储值
             */
            set(key, value) {
                try {
                    localStorage.setItem(key, JSON.stringify(value));
                } catch (error) {
                    console.error('Storage set error:', error);
                }
            },

            /**
             * 删除存储项
             * @param {string} key - 存储键
             */
            remove(key) {
                try {
                    localStorage.removeItem(key);
                } catch (error) {
                    console.error('Storage remove error:', error);
                }
            },

            /**
             * 清空所有存储
             */
            clear() {
                try {
                    localStorage.clear();
                } catch (error) {
                    console.error('Storage clear error:', error);
                }
            }
        };
    }

    /**
     * 路由相关配置
     */
    static get router() {
        return {
            defaultRoute: '/',
            loginRoute: '/auth/login',
            notFoundRoute: '/pages/notfound',
            accessDeniedRoute: '/auth/access'
        };
    }

    /**
     * UI相关配置
     */
    static get ui() {
        return {
            pageSize: 20,
            debounceDelay: 300,
            toastDuration: 3000,
            loadingDelay: 200,

            // 分页配置
            pagination: {
                defaultPageSize: 20,
                pageSizeOptions: [10, 20, 50, 100],
                showSizeChanger: true,
                showQuickJumper: true
            },

            // 表格配置
            table: {
                striped: true,
                bordered: false,
                hover: true,
                responsive: true,
                size: 'default'
            }
        };
    }

    /**
     * 验证配置
     */
    static get validation() {
        return {
            rules: {
                required: { required: true, message: '此字段为必填项' },
                email: {
                    type: 'email',
                    message: '请输入有效的邮箱地址'
                },
                phone: {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入有效的手机号码'
                },
                password: {
                    min: 6,
                    message: '密码长度至少6位'
                }
            }
        };
    }
}

// 导出配置实例
export default AppConfig;
